#include <iostream>
#include <unistd.h>
using namespace std;
#include <cassert>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

int main()
{

    // 创建管道
    int fds[2];
    int n = pipe(fds);

    int id = fork();
    if (id == 0)
    {
        // 子进程:写数据
        close(fds[0]);
        while (1)
        {
            char buffer[128];
            snprintf(buffer, sizeof(buffer), "我是子进程，正在和你通信");
            write(fds[1], buffer, sizeof(buffer));
           // sleep(1);
        }
        close(fds[1]);
        exit(1);
    }

    // 父进程:读取数据
    close(fds[1]);
    char buffer[128];
    while (1)
    {
        ssize_t n = read(fds[0], buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
        }
        cout << "子进程说：" << buffer << endl;
        exit(1);//把读端关闭，这样写端也会被os通过发送信号的方式关闭
        //sleep(1);
    }
    // 进程等待
    int status = 0;
    n = waitpid(id,&status,0);

    if(n > 0){
        cout<<"success wait"<<endl;
    }



    return 0;
}